הנכות 1 תואיגש םע תודדומתהו תואלול,םי : כרעמ 2 לוגרת

Similar documents
הנכות 1 תואיגש םע תודדומתהו תואלול,םיכרעמ : לו 2 גרת

תוכנה 1 תרגול 2: מערכים ומבני בקרה

תוכנה 1 מערכים. Array Creation and Initialization. Array Declaration. Loop through Arrays. Array Creation and Initialization

תוכנה 1 3 תרגול מס' מערכים ומבני בקרה

תוכנה 1 מערכים. Array Creation and Initialization. Array Declaration. Array Creation and Initialization. Loop through Arrays

תוכנה 1 תרגול 2: מערכים, מבני בקרה ושגיאות

תוכנה 1 טיפוסי השפה טיפוסים לא פרימיטיביים הטיפוסים הפרימיטיביים מחרוזות המרה למספרים תרגול 2: טיפוסי שפה, מחרוזות, מערכים ושגיאות

Ohad Barzilay and Oranit Dror

Sun שיטת הגמל: "isodd" "is_odd" Sun. תוכנה 1 בשפת Java אוניברסיטת תל אביב

תוכנה 1 סמסטר א' תשע"א

הנכות 1 םוכיס לוגרת 14 1

מערכים שעור מס. 4 כל הזכויות שמורות דר ' דרור טובי המרכז האוניברסיטאי אריאל 1

לתיכנות עם MATLAB Lecture 5: Boolean logic and Boolean expressions

הנכות 1 םוכיס לוגרת 13 1

תוכנה 1. תרגול מספר 11: Static vs. Dynamic Binding מחלקות מקוננות Nested Classes

לתיכנות עם MATLAB Lecture 5: Boolean logic and Boolean expressions

מבוא לתכנות ב- JAVA תרגול 7

הנכות 1 םוכיס לוגרת 13 1

תזכורת: עץבינארי מבוא למדעי המחשב הרצאה 24: עצי חיפוש בינאריים

Practical Session - Heap

Data Types. 9. Types. a collection of values and the definition of one or more operations that can be performed on those values

הקלחמ ה תמרב ת ונ וכ ת (static members ) יליזרב דהוא Java תפשב ם דקת מ תונכת ביבא ל ת תטיסרבינוא

Java Programming Language Mr.Rungrote Phonkam

COMP-202: Foundations of Programming. Lecture 13: Recursion Sandeep Manjanna, Summer 2015

תור שימושים בעולם התוכנה

תוכנה 1 * לא בהכרח בסדר הזה

היצביט ומ - ןוכית ת וי נבת

לתיכנות עם MATLAB Lecture 5: Boolean logic and Boolean expressions

Recursion Enums. Basics of Programming 1. Department of Networked Systems and Services G. Horváth, A.B. Nagy, Z. Zsóka, P. Fiala, A.

Pace University. Fundamental Concepts of CS121 1

משתנים שעור מס. 2 כל הזכויות שמורות דר ' דרור טובי המרכז האוניברסיטאי אריאל 1

CSE 341 Section Handout #6 Cheat Sheet

הנכות 1 םוכיס לוגרת 13 1

תוכנה 1 * לא בהכרח בסדר הזה

תכנות מונחה עצמים משחקים תשע"ו

CMIS 102 Hands-On Lab

CS Programming I: Arrays

Syntax and Variables

Advanced Computer Programming

Notes - Recursion. A geeky definition of recursion is as follows: Recursion see Recursion.

High Performance Computing

Arrays III and Enumerated Types

34. Recursion. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Answers to review questions from Chapter 2

Scientific Programming in C X. More features & Fortran interface

Practical Session No. 14 Topological sort,amortized Analysis

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

i.e.: n! = n (n 1)

מחרוזות ב Java ותכנות מונחה בדיקות )Test Driven Development(

Recursion CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011

ASP.Net Web API.

II. Compiling and launching from Command-Line, IDE A simple JAVA program

COS 126 Midterm 1 Written Exam Fall 2011

Wentworth Institute of Technology COMP1050 Computer Science II Spring 2017 Derbinsky. Recursion. Lecture 13. Recursion

מבוא לתכנות ב- JAVA מעבדה 3. Ipc161-lab3

תוכנה 1 תרגול מספר 13

תוכנה 1 תרגול מספר 13

CS1 Recitation. Week 2

Recursion. Overview. Mathematical induction. Hello recursion. Recursion. Example applications. Goal: Compute factorial N! = 1 * 2 * 3...

News and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.!

Definition: Data Type A data type is a collection of values and the definition of one or more operations on those values.

Lecture 6. Drinking. Nested if. Nested if s reprise. The boolean data type. More complex selection statements: switch. Examples.

מצליחה. 1. int fork-bomb() 2. { 3. fork(); 4. fork() && fork() fork(); 5. fork(); printf("bla\n"); 8. return 0; 9. }

מבוא לתכנות תוכנית שעור מס. 1 1 דר' דרור טובי, המרכז האוניברסיטאי אריאל בשומרון.

תרשים המחלקות ותרשים העצמים

Programming for Engineers in Python

Programming for Engineers in Python

More Binary Search Trees AVL Trees. CS300 Data Structures (Fall 2013)

Introduction to Programming Using Java (98-388)

תרגול 3 מערכים ופונקציות

Instructor training course schedule v3 Confirmed courses due completion by 31 st July 2019

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

More BSTs & AVL Trees bstdelete

Arrays. Arrays. Wolfgang Schreiner Research Institute for Symbolic Computation (RISC) Johannes Kepler University, Linz, Austria

ECSE 321 Assignment 2

Exam 2 ITEC 120 Principles of Computer Science I Spring: 2017

CS313D: ADVANCED PROGRAMMING LANGUAGE

Array. Array Declaration:

Purpose of the Simulated function

Lecture 14 CSE11 Fall 2013 For loops, Do While, Break, Continue

1. Introduction to Java for JAS

CSI33 Data Structures

All King County Summary Report

מבוא למדעי המחשב תרגול 8 רשימה משורשרת כללית, Comparator

Arrays. CSE 142, Summer 2002 Computer Programming 1.

תוכנה 1 מבני נתונים גנריים

Recursion. Fundamentals of Computer Science

מבוא לתכנות ב- JAVA תרגול 6

recursive algorithms 1

Recursive Definitions

What you learned so far. Loops & Arrays efficiency for statements while statements. Assignment Plan. Required Reading. Objective 2/3/2018

מבוא לתכנות ב- JAVA תרגול 5. Ipc161- practical session 5

סכום (סדרת ערכים) אחרת - דוגמא: סכום-ספרות (num) אם < 10 num החזר 1 או אם = 0 = num החזר 0 public static int numofdigits (int num)

Java Bytecode (binary file)

PROGRAMMING FUNDAMENTALS

This report is based on sampled data. Jun 1 Jul 6 Aug 10 Sep 14 Oct 19 Nov 23 Dec 28 Feb 1 Mar 8 Apr 12 May 17 Ju

Seattle (NWMLS Areas: 140, 380, 385, 390, 700, 701, 705, 710) Summary

Question: Total Points: Score:

Recursion. General Algorithm for Recursion. When to use and not use Recursion. Recursion Removal. Examples

Computer Programming, I. Laboratory Manual. Final Exam Solution

Transcription:

תוכנה 1 תרגול 2: מערכים, לולאות והתמודדות עם שגיאות

מערכים

מערכים Array: A fixed-length data structure for storing multiple values of the same type Example from last week: An array of odd numbers: Indices (start from 0) 0 1 2 3 4 5 6 7 odds: 1 3 5 7 9 11 13 15 The type of all elements is int odds.length == 8 The value of the element at index 4 is 9: odds[4] == 9 3

Array Variables An array is denoted by the [] notation Examples: int[] odds; String[] names; int[][] matrix; // an array of arrays matrix: 4

Array Creation and Initialization What is the output of the following code: int[] odds = new int[8]; for (int i = 0; i < odds.length; i++) { System.out.print(odds[i] + " "); odds[i] = 2 * i + 1; System.out.print(odds[i] + " "); Output: Array creation: all elements get the default value for their type (0 for int) 0 1 0 3 0 5 0 7 0 9 0 11 0 13 0 15 5

Array Creation and Initialization Creating and initializing small arrays with a-priori known values: int[] odds = {1,3,5,7,9,11,13,15; String[] months = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sep", "Oct", "Nov", "Dec"; Jan months: 6

Loop through Arrays By promoting the array's index: for (int i = 0; i < months.length; i++) { foreach: System.out.println(months[i]); for (String month: months) { System.out.println(month); The variable month is assigned the next element in each iteration 7

Operations on arrays The class Arrays provide operations on array Copy Sort Search Fill... java.util.arrays http://docs.oracle.com/javase/8/docs/api/index.html?java/util/arr ays.html 8

Copying Arrays Assume: int[] array1 = {1,2,3; int[] array2 = {8,7,6,5; Naïve copy: array1 = array2; 8,7,6,5 array2 1,2,3 array1 What s wrong with this solution? 9

Copying Arrays Arrays.copyOf 1 st argument: the original array 2 nd argument: the length of the copy int[] arr1 = {1, 2, 3; int[] arr2 = Arrays.copyOf(arr1, arr1.length); Arrays.copyOfRange 1 st argument: the original array 2 nd initial index of the range to be copied, inclusive 3 rd argument: final index of the range to be copied, exclusive 10

Question What is the output of the following code: int[] odds = {1, 3, 5, 7, 9, 11, 13, 15; int newodds[] = Arrays.copyOfRange(odds, 1, odds.length); for (int odd: newodds) { System.out.print(odd + " "); Output: 3 5 7 9 11 13 15 11

2D Arrays There are no 2D arrays in Java but you can build an array of arrays: char[][] board = new char[3][]; for (int i = 0; i < 3; i++) board[i] = new char[3]; Or equivalently: char[][] board = new char[3][3]; board 12

2D Arrays A more compact table: int[][] table = new int[10][]; for (int i = 0; i < 10; i++) { table[i] = new int[i + 1]; for (int j = 0; j <= i; j++) { table[i][j] = (i + 1) * (j + 1); 3 6 9 2 4 table 1 13

לולאות ותנאים

Fibonacci Fibonacci series 1, 1, 2, 3, 5, 8, 13, 21, 34 Definition: fib(0) = 1 fib(1) = 1 fib(n) = fib(n-1) + fib(n-2) en.wikipedia.org/wiki/fibonacci_number

If-Else Statement public class Fibonacci { /** Returns the n-th Fibonacci element */ public static int computeelement(int n) { if (n==0) return 1; else if (n==1) return 1; else return computeelement(n-1) + computeelement(n-2); Can be removed Assumption: n 0 16

Switch Statement public class Fibonacci { /** Returns the n-th Fibonacci element */ public static int computeelement(int n) { switch(n) { case 0: return 1; case 1: return 1; default: Assumption: n 0 can be placed outside the switch return computeelement(n-1) + computeelement(n-2); 17

Switch Statement public class Fibonacci { /** Returns the n-th Fibonacci element */ public static int computeelement(int n) { switch(n) { case 0: return 1; case 1: return 1; break; default: Compilation Error: Unreachable Code Assumption: n 0 return computeelement(n-1) + computeelement(n-2); 18

Iterative Fibonacci A loop instead of a recursion static int computeelement(int n) { if (n == 0 n == 1) return 1; int prev = 1; int prevprev = 1; int curr = 2; Assumption: n 0 for (int i = 2 ; i < n ; i++) { curr = prev + prevprev; Must be initialized. prevprev = prev; Why? prev = curr; curr = prev + prevprev; return curr; 1 1 2 1 2 3 2 3 5 prevprev prev curr 19

נתונים במקום חישוב בתרגום רקורסיה ללולאה אנו משתמשים במשתני עזר לשמירת המצב curr, prev ו- prevprev הלולאה "זוכרת" את הנקודה שבה אנו נמצאים בתהליך החישוב. דיון: יעילות לעומת פשטות. 20

For Loop Printing the first n elements: public class Fibonacci { public static int computeelement(int n) { It is better to use args[0] public static void main(string[] args) { for(int i = 0 ; i < 10 ; i++) { System.out.println(computeElement(i)); 21

מודולריות, שכפול קוד ויעילות יש כאן חוסר יעילות מסוים: לולאת ה- for חוזרת גם ב- main וגם ב-.computeElement לכאורה, במעבר אחד ניתן גם לחשב את האיברים וגם להדפיס אותם כמו כן כדי לחשב איבר בסדרה איננו משתמשים בתוצאות שכבר חישבנו )של איברים קודמים( ומתחילים כל חישוב מתחילתו 22

מודולריות, שכפול קוד ויעילות צריכה לעשות דבר אחד בדיוק! והדפסה פוגע במודולריות )מדוע?( מתודה )פונקציה( ערוב של חישוב היזהרו משכפול קוד! קטע קוד דומה המופיע בשתי פונקציות שונות יגרום במוקדם או במאוחר לבאג בתוכנית )מדוע?( את בעיית היעילות )הוספת מנגנון )memoization אפשר לפתור בעזרת מערכים )תרגיל( 23

for vs. while The following two statements are almost equivalent: Variable i is not defined outside the for block for(int i = 0 ; i < n ; i++) System.out.println(computeElement(i)); int i=0; while (i < n) { System.out.println(computeElement(i)); i++; 24

while vs. do while The following two statements are equivalent if and only if n>0 : int i=0; while (i < n) { System.out.println(computeElement(i)); i++; int i=0; do { System.out.println(computeElement(i)); i++; while (i>n(; 25

התמודדות עם שגיאות

Compilation vs. Runtime Errors Syntax error on token "Class", class expected שגיאות קומפילציה )הידור(: שגיאות שניתן "לתפוס" בעת קריאת הקובץ והפיכתו ל- bytecode ע"י המהדר Class MyClass { void f() { int n=10; void g() { int m = 20; int i; System.out.println(i); דוגמאות: Syntax error, insert "" to complete MethodBody בדרך כלל קשורות ל: תחביר, תאימות טיפוסים, הגדרה לפני שימוש 27

Compilation vs. Runtime Errors שגיאות זמן ריצה: לא ניתן לדעת שתהיה שגיאה במקום ספציפי בזמן ההידור )קומפילציה( a = new int[20]; int a[] = new int[10]; a[15] = 10; דוגמאות: String s = null; System.out.println(s.length()); מתקשר למנגנון החריגים,)exceptions( עליו נלמד בהמשך 28

Compilation vs. Runtime Errors האם יש עוד סוג של טעויות? כן, הכי גרועות, טעויות לוגיות בתוכנית public class Factorial { /** calculate x! **/ public static int factorial(int x) { int f = 0; for (int i = 2; i <= x; i++) f = f * i; return f; 29

The Debugger Some programs may compile correctly, yet not produce the desirable results These programs are valid and correct Java programs, yet not the programs we meant to write! The debugger can be used to follow the program step by step and may help detecting bugs in an already compiled program

Debugger Add Breakpoint Right click on the desired line Toggle Breakpoint

Debugger Start Debugging debug (F11) breakpoint

Debugger Debug Perspective

Debugger Debugging Current state Back to Java perspective Current location

Debugger Debugging

Using the Debugger: Video Tutorial מצגות וידאו http://eclipsetutorial.sourceforge.net/debugger.html מדריך עדכני יותר http://www.vogella.com/tutorials/eclipsedebugging/articl e.html הקישורים נמצאים גם באתר הקורס 36

הסוף...